import { useCallback } from "react";
import { CreateArticleDto, UpdateArticleDto } from "@/types/article";
import { articleApi } from "@/api";
import { message } from "antd";
import { useAppStore } from "@/stores";
import { useTranslation } from "react-i18next";

export const useArticle = () => {
  const { t } = useTranslation();
  const setLoading = useAppStore((state) => state.setLoading);

  const fetchArticles = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await articleApi.list();
      return data;
    } catch (error) {
      message.error(t("article.action.fetchListError"));
      return [];
    } finally {
      setLoading(false);
    }
  }, [setLoading, t]);

  const createArticle = useCallback(
    async (data: CreateArticleDto) => {
      setLoading(true);
      try {
        const { data: result } = await articleApi.create(data);
        message.success(t("article.action.createSuccess"));
        return result;
      } catch (error) {
        message.error(t("article.action.createError"));
        return null;
      } finally {
        setLoading(false);
      }
    },
    [setLoading, t]
  );

  const updateArticle = useCallback(
    async (id: string, data: UpdateArticleDto) => {
      setLoading(true);
      try {
        const { data: result } = await articleApi.update(id, data);
        message.success(t("article.action.updateSuccess"));
        return result;
      } catch (error) {
        message.error(t("article.action.updateError"));
        return null;
      } finally {
        setLoading(false);
      }
    },
    [setLoading, t]
  );

  const deleteArticle = useCallback(
    async (id: string) => {
      setLoading(true);
      try {
        await articleApi.delete(id);
        message.success(t("article.action.deleteSuccess"));
        return true;
      } catch (error) {
        message.error(t("article.action.deleteError"));
        return false;
      } finally {
        setLoading(false);
      }
    },
    [setLoading, t]
  );

  return {
    fetchArticles,
    createArticle,
    updateArticle,
    deleteArticle,
  };
};
